<script>
import request from "@/utils/request";
export default {
  name: "Auction",
  data() {
    return {
      user: localStorage.getItem("honey-user") ? JSON.parse(localStorage.getItem("honey-user")) : {},
      item: {
        auctionId: '',
        auctionName: '',
        auctionDesc: '',
        auctionStartTime: '',
        auctionEndTime: '',
        auctionStartPrice: 0 // 确保初始值是数字
      },
      maxAuctionPrice: 0,
      bids: [],
      paiFrom:{
        userId: '',
        auctionId: this.$route.query.auctionId,
        auctionTime: new Date().toLocaleString(),
        auctionPrice:'',
      }
    };
  },
  methods: {
    selectid() {
      const params = {
        auctionId: this.$route.query.auctionId
      };
      request.get("/selectById", { params })
          .then((res) => {
            console.log(res);
            this.item = {
              ...res,
            };
          })
          .catch((err) => {
            console.error("请求失败:", err);
          });
    },
    selectauction() {
      const params = {
        auctionId: this.$route.query.auctionId
      };
      request.get("/selectRecord", { params })
          .then((res) => {
            console.log(res);
            this.bids = res; // 确认这里只将数据赋值给 bids
            this.maxAuctionPrice = this.maxPrice; // 更新最大竞拍价格
          })
          .catch((err) => {
            console.error("请求失败:", err);
          });
    },
    refreshPage() {
      window.location.reload();
    },
    returnToList() {
      this.$router.push("/index");
    },
    logout() {
      localStorage.removeItem("honey-user");
      this.$router.push("/");
      this.$message.success('退出成功');
    },
    pai() {
      if (this.paiFrom.auctionPrice <= this.item.auctionStartPrice) {
      this.$message.error('竞拍价格必须大于起拍价');
      return; // 直接返回，避免继续执行后续逻辑
      }
      if (this.paiFrom.auctionPrice <= this.maxAuctionPrice) {
        this.$message.error('竞拍价格必须大于当前最高竞拍价格');
        return;
      }
      // 设置用户 ID
      this.paiFrom.userId = this.user.userId;
      // 发送请求
      this.$request.post('/add', this.paiFrom).then(res => {
        if (res.code === '200') {
          this.selectauction();
          this.$message.success('添加成功');
        } else {
          this.$message.error(res.msg);
        }
      }).catch(error => {
        console.error('请求失败:', error);
      });
    }
  },
  created() {

  },
  mounted() {
    this.selectid(); // 在组件挂载后调用该方法
    this.selectauction();
  },
  computed: {
    maxPrice() {
      // 找出bids数组中竞拍价格的最大值
      if(this.bids.length === 0) return 0;
      return Math.max(...this.bids.map(bid => parseFloat(bid.auctionPrice)));
    }
  },
  watch: {
    // 监听 bids 数组变化，更新最大竞拍价格
    bids: {
      handler(newVal) {
        this.maxAuctionPrice = this.maxPrice;
      },
      deep: true // 确保可以检测数组内部的变化
    }
  },
};
</script>

<template>
  <el-container class="wrap">
    <el-header>
      <el-row>
        <el-col :span="12">
          <h1>在线拍卖系统</h1>
        </el-col>
        <el-col :span="12" class="align-right">
          {{user.userName}}
          <el-button type="text" @click="logout">注销</el-button>
        </el-col>
      </el-row>
    </el-header>
    <el-container>
      <el-main>
        <el-row :gutter="20" class="top10">
          <el-col :span="15">
            <el-card>
              <ul class="item-details" style="list-style: none;font-size: 120%">
                <li><strong>名称：</strong>{{ item.auctionName }}</li>
                <li><strong>描述：</strong>{{ item.auctionDesc }}</li>
                <li><strong>开始时间：</strong>{{ item.auctionStartTime }}</li>
                <li><strong>结束时间：</strong>{{ item.auctionEndTime }}</li>
                <li><strong>起拍价：</strong>{{item.auctionStartPrice.toFixed(2)}}</li>
              </ul>
            </el-card>
          </el-col>
          <el-col :span="2">
            &nbsp;
          </el-col>
          <el-col :span="7">
            <el-card>
              <img src="@/assets/images/ad20.jpg" style="width: 100%;" />
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="top10">
          <el-col>
            <el-card class="top10">
              <el-form ref="form" >
                <el-form-item label="出价：" :model="paiFrom" ref="paiFroms">
                  <el-input style="width: 60%" size="mini" v-model="paiFrom.auctionPrice"></el-input>
                  <el-button type="primary" style="margin-left: 10px" size="mini" @click="pai">竞 拍</el-button>
                </el-form-item>
                <el-form-item >
                  <el-button type="primary" size="mini" @click="refreshPage">刷新</el-button>
                  <el-button type="primary" size="mini" @click="returnToList">返回列表</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="top10">
          <el-col :span="15">
            <el-card class="top10">
              <h3>出价记录</h3>
              <el-table :data="bids" stripe>
                <el-table-column prop="auctionTime" label="竞拍时间" />
                <el-table-column prop="auctionPrice" label="竞拍价格" />
                <el-table-column prop="user.userName" label="竞拍人" />
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </el-container>
</template>

<style scoped>
.align-right {
  text-align: right;
}

.item-details {
  list-style: none;
  padding: 0;
}

.item-details li {
  margin: 10px 0;
}

.top10 {
  margin-top: 10px;
}
</style>